package com.dailyblue.java.spring.cloud.jwt.gateway.filter;

import com.alibaba.fastjson.JSONArray;
import com.dailyblue.java.spring.cloud.example.commons.bean.User;
import com.dailyblue.java.spring.cloud.example.commons.util.JsonResult;
import com.dailyblue.java.spring.cloud.example.commons.util.JwtConfig;
import com.dailyblue.java.spring.cloud.example.commons.util.ResultCode;
import com.dailyblue.java.spring.cloud.example.commons.util.ResultTool;
import com.dailyblue.java.spring.cloud.jwt.gateway.service.UserService;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

@Component
public class LoginGlobalFilter implements GlobalFilter, Ordered {
    @Resource
    private UserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        String uri = request.getURI().toString();
        System.out.println(uri);
        if (!uri.contains("/login")) {
            chain.filter(exchange);
        }
        String name = request.getQueryParams().get("name").get(0);
        String pass = request.getQueryParams().get("pass").get(0);
        JsonResult<User> result = userService.login(name, pass);
        if (!result.getSuccess()) {
            return error(exchange);
        }
        String token = JwtConfig.getJwtToken(result.getData());
        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        valueOperations.set("token:" + result.getData().getId(), token);
        return success(exchange, token);
    }

    private Mono<Void> error(ServerWebExchange exchange) {
        // 浏览器没有携带token
        // 获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        // 设置响应状态码
        response.setStatusCode(HttpStatus.resolve(401));
        // 设置返回格式
        response.getHeaders().set("ContentType", "application/json;charset=utf-8");
        // 设置返回的内容
        JsonResult result = ResultTool.fail(ResultCode.USER_ACCOUNT_DISABLE);
        String str = JSONArray.toJSONString(result);
        DataBuffer data = response.bufferFactory().wrap(str.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(data));
    }

    private Mono<Void> success(ServerWebExchange exchange, String token) {
        // 浏览器没有携带token
        // 获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        // 设置响应状态码
        response.setStatusCode(HttpStatus.resolve(200));
        // 设置返回格式
        response.getHeaders().set("ContentType", "application/json;charset=utf-8");
        // 设置返回的内容
        JsonResult result = ResultTool.success(token);
        String str = JSONArray.toJSONString(result);
        DataBuffer data = response.bufferFactory().wrap(str.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(data));
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
